import React, { useState, useEffect, useRef } from 'react';
import { Modal, Row, Col, Button, message } from 'antd';
import { AUDIT_NODE, AUDIT_STATUS, ModalType } from '@/utils/trainUtil';
import type { FormInstance } from 'antd';
import classnames from 'classnames';
import { getToken } from '@/utils/storage';
import ProForm, { ProFormText, ProFormUploadButton, ProFormList } from '@ant-design/pro-form';
import { postSubmitSupplementaryMaterials } from '@/services/PersonalCenter/applicationQuery';
import styles from './index.less';

interface ApplicationDetailModalProps {
  type?: string;
  visible?: boolean;
  closeModal: any;
  data: any;
  onSuccess: () => void;
}

const ApplicationDetailModal: React.FC<ApplicationDetailModalProps> = (props) => {
  const { type, visible, closeModal, data, onSuccess } = props;
  const [projectInfo, setProjectInfo] = useState<{ label: string; value: string | number }[]>();
  const formRef = useRef<FormInstance>();
  const isDetailAdd = type === ModalType.ADD;
  const handleCancel = () => {
    closeModal();
    formRef.current?.resetFields();
  };
  const handleOK = () => {
    closeModal();
    formRef.current?.resetFields();
  };
  const handleSubmit = async () => {
    const values = await formRef.current?.validateFields();
    const { policyInfoApplyMaterial } = values;
    const policyInfoApplyMaterialVos = [];
    policyInfoApplyMaterial?.forEach((item: any) => {
      if (item.uploadfile) {
        if (item.uploadfile.length > 0) {
          policyInfoApplyMaterialVos.push({
            fileName: item.uploadfile[0].name,
            title: item?.fileName,
            url: item.uploadfile[0].response.results,
          });
        }
      }
    });
    try {
      const { errorCode } = await postSubmitSupplementaryMaterials({
        applyId: data?.id,
        policyInfoApplyMaterialVos,
      });
      if (errorCode === 0) {
        closeModal();
        formRef.current?.resetFields();
        onSuccess();
        message.success('提交补充申请材料成功！');
      }
    } catch (e) {
      message.error('提交失败,请联系管理员');
    }
  };
  useEffect(() => {
    if (data) {
      setProjectInfo([
        {
          label: '申请项目名称：',
          value: data.matterTitle,
        },
        {
          label: '单位名称：',
          value: data.companyName,
        },
        {
          label: '基本户银行：',
          value: data.basicAccount,
        },
        {
          label: '经办人：',
          value: data.manager,
        },
        {
          label: '手机号：',
          value: data.managerPhone,
        },
        {
          label: 'E-mail：',
          value: data.managerEmail,
        },
        {
          label: '办公电话：',
          value: data.managerTel,
        },
        {
          label: '资助标准：',
          value: data.fundingCriteria,
        },
        {
          label: '本次申请金额（元）：',
          value: data.applyAmount,
        },
        {
          label: '兑现事项情况说明：',
          value: data.descriptionRedemptionMatters,
        },
      ]);
    }
  }, [data]);
  const getFooterButtons = (type) => {
    if (type === 'detailAdd') {
      return [
        <Button onClick={() => handleCancel()}>取消</Button>,
        <Button type="primary" onClick={() => handleSubmit()}>
          提交
        </Button>,
      ];
    }
    return [
      <Button onClick={() => handleCancel()}>取消</Button>,
      <Button type="primary" onClick={() => handleOK()}>
        确定
      </Button>,
    ];
  };
  return (
    <Modal
      visible={visible}
      title="事项详情"
      width={700}
      onCancel={handleCancel}
      onOk={handleOK}
      destroyOnClose={true}
      footer={getFooterButtons(type)}
      className={styles.applicationDetailModal}
    >
      {projectInfo?.map((info) => {
        return (
          <Row className={styles.fixedItem}>
            <Col span={8} className={styles.itemLabel}>
              {info.label}
            </Col>
            <Col span={16} className={styles.itemContent}>
              {info.value}
            </Col>
          </Row>
        );
      })}
      <Row className={styles.fixedItem}>
        <Col span={8} className={styles.itemLabel}>
          申报材料清单：
        </Col>
        <Col span={16}>
          {data?.policyInfoApplyMaterialVos?.map((material) => {
            return (
              <div className={styles.materialItem}>
                <div className={styles.materialTitle} title={material.title}>
                  {material.title ? material.title : '未命名文件'}
                </div>
                <span>：</span>
                <a
                  href={material.url}
                  target={'_blank'}
                  className={styles.materialPdfTitle}
                  title={material.fileName}
                >
                  {material.fileName}
                </a>
              </div>
            );
          })}
        </Col>
      </Row>
      <Row className={styles.fixedItem}>
        <Col span={8} className={styles.itemLabel}>
          审核信息：
        </Col>
        <Col span={16} className={styles.processCol}>
          {data?.policyAuditProcessVos?.map((process, index) => {
            return (
              <div className={styles.processItem}>
                <div className={styles.dotLine}>
                  <div className={styles.dot}></div>
                  {data?.policyAuditProcessVos?.length - 1 !== index && (
                    <div className={styles.line}></div>
                  )}
                </div>
                <div className={styles.approveInfo}>
                  <div className={styles.approveItem}>{AUDIT_NODE[process.currentProcessNode]}</div>
                  <div className={styles.approveItem}>{`${process.approvePersonName}（${
                    AUDIT_STATUS[process.currentAuditStatus]
                  }）`}</div>
                  {process.approveSuggestion && (
                    <div
                      className={classnames(`${styles.approveItem} ${styles.suggestion}`)}
                      title={process.approveSuggestion}
                    >
                      审核建议：{process.approveSuggestion}
                    </div>
                  )}
                  {process.suggestedAmount > 0 && (
                    <div className={styles.approveItem}>
                      审核金额（元）：{process.suggestedAmount}
                    </div>
                  )}
                </div>
                <div className={styles.approveTime}>{process.approveTime}</div>
              </div>
            );
          })}
        </Col>
      </Row>
      {isDetailAdd && (
        <Row className={styles.AddSupplementaryMaterials}>
          <Col span={24}>
            <ProForm
              formRef={formRef}
              layout="horizontal"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              submitter={false}
            >
              <ProFormList
                rules={[
                  {
                    required: true,
                    message: '请添加申报材料',
                  },
                ]}
                name="policyInfoApplyMaterial"
                label="申报材料"
                initialValue={[{}]}
                creatorButtonProps={true}
                copyIconProps={false}
                deleteIconProps={true}
                layout={'vertical'}
              >
                <ProForm.Group size="large">
                  <ProFormText
                    className={styles.addFileName}
                    rules={[
                      {
                        required: true,
                        message: '申报材料名称不能为空',
                      },
                    ]}
                    width="md"
                    name="fileName"
                    placeholder="请输入申报材料名称"
                  />
                  <ProFormUploadButton
                    id="id"
                    fieldProps={{
                      name: 'file',
                      headers: {
                        'Access-Token': getToken() || '',
                      },
                      listType: 'text',
                    }}
                    max={5}
                    accept={'.pdf'}
                    name="uploadfile"
                    action={`${WEB_DOMAIN.apiDomain}/files/uploadFile`}
                  />
                </ProForm.Group>
              </ProFormList>
            </ProForm>
          </Col>
        </Row>
      )}
    </Modal>
  );
};
export default ApplicationDetailModal;
